package elcs.controller;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import elcs.board.model.BoardService;
import elcs.board.model.BoardVO;
import elcs.board.model.ListVO;
import elcs.rank.model.RankService;
import elcs.rank.model.RankVO;
import elcs.reply.model.ReplyService;
import elcs.reply.model.ReplyVO;

@Controller
public class BoardController {
	@Resource(name = "boardServiceImpl")
	private BoardService boardService;
	@Resource(name = "replyServiceImpl")
	private ReplyService replyService;
	@Resource(name = "rankServiceImpl")
	private RankService rankService;

	// private String
	// path="C:\\java-kosta\\finalproject-workspace\\ELCS_12_10-pjh-7\\WebContent\\upload\\";
	private String path;

	public void setPath(String path) {
		this.path = path;
		System.out.println(path + " di...");
	}

	@RequestMapping("/view.do")
	public ModelAndView getViewList(BoardVO bvo, HttpServletRequest request)
			throws Exception {
		ModelAndView mv = new ModelAndView();

		String pageNo = request.getParameter("pageNo");

		Map map = new HashMap();
		map.put("head", bvo.getHead());
		map.put("pageNo", pageNo);
		map.put("category", bvo.getCategory());
		String type = request.getParameter("type");

		ListVO lvo = boardService.getViewList(map);

		if (type.equals("reply")) {
			if (lvo.getList().isEmpty()) {

				mv.addObject("bvo", bvo);
				mv.setViewName("reply/list.board");
			} else {

				mv.addObject("lvo", lvo);
				mv.setViewName("reply/list.board");
			}
		} else if (type.equals("basic")) {
			if (lvo.getList().isEmpty()) {

				mv.addObject("bvo", bvo);
				mv.setViewName("basic/list.board");
			} else {
				mv.addObject("lvo", lvo);
				mv.setViewName("basic/list.board");
			}
		} else if (type.equals("answer")) {

			if (lvo.getList().isEmpty()) {

				mv.addObject("bvo", bvo);
				mv.setViewName("answer/list.board");
			} else {
				mv.addObject("lvo", lvo);
				mv.setViewName("answer/list.board");
			}
		}
		return mv;
	}
	@RequestMapping("/today.do")
	@ResponseBody
	public List<BoardVO> todayView(BoardVO bvo) throws Exception{
		
		List<BoardVO> list=boardService.todayView(bvo);
		
		
		return list;
	}
	

	@RequestMapping("/board/detail.do")
	public ModelAndView detailView(BoardVO bvo, HttpServletRequest request)
			throws Exception {
		ModelAndView mv = new ModelAndView();
		String type = request.getParameter("type");

		boardService.addCountView(bvo);
		bvo = boardService.detailView(bvo);
		List<ReplyVO> list = replyService.replyList(bvo);

		Map map = new HashMap();
		map.put("bvo", bvo);
		map.put("list", list);

		if (type.equals("reply")) {
			mv.addObject("map", map);
			
			mv.setViewName("reply/detail.board");
		} else if (type.equals("basic")) {
			mv.addObject("bvo", bvo);
			mv.setViewName("basic/detail.board");
		} else if (type.equals("answer")) {
			mv.addObject("bvo", bvo);
			mv.setViewName("answer/detail.board");
		}

		return mv;
	}

	@RequestMapping("/board/delete.do")
	public ModelAndView deleteBoard(BoardVO bvo, HttpServletRequest request)
			throws Exception {
		ModelAndView mv = new ModelAndView();
		String type = request.getParameter("type");

		String newfilename = bvo.getNewfilename();
		// 업로드한 파일이 존재하면
		if (newfilename != null && newfilename.equals("") == false) {
			deleteFile(newfilename);// 파일을 삭제
		}

		boardService.deleteBoard(bvo);

		if (type.equals("reply")) {

			mv.setViewName("redirect:/view.do?head=" + bvo.getHead()
					+ "&type=reply&category=" + bvo.getCategory());
		} else if (type.equals("basic")) {
			mv.setViewName("redirect:/view.do?head=" + bvo.getHead()
					+ "&type=basic&category=" + bvo.getCategory());
		} else if (type.equals("answer")) {
			mv.setViewName("redirect:/view.do?head=" + bvo.getHead()
					+ "&type=answer&category=" + bvo.getCategory());
		}

		return mv;
	}

	@RequestMapping("/board/updateInfo.do")
	public ModelAndView updateInfo(BoardVO bvo, HttpServletRequest request)
			throws Exception {
		ModelAndView mv = new ModelAndView();
		bvo = boardService.detailView(bvo);

		String type = request.getParameter("type");
		if (type.equals("reply")) {
			mv.addObject("bvo", bvo);
			mv.setViewName("reply/updateinfo.board");
		} else if (type.equals("basic")) {
			mv.addObject("bvo", bvo);
			mv.setViewName("basic/updateinfo.board");
		} else if (type.equals("answer")) {
			mv.addObject("bvo", bvo);
			mv.setViewName("answer/updateinfo.board");
		}

		return mv;
	}

	@RequestMapping("/board/writeInfo.do")
	public ModelAndView writeForm(BoardVO bvo, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		String type = request.getParameter("type");

		if (type.equals("reply")) {

			mv.addObject("bvo", bvo);
			mv.setViewName("reply/writeinfo.board");
		} else if (type.equals("basic")) {

			mv.addObject("bvo", bvo);
			mv.setViewName("basic/writeinfo.board");
		} else if (type.equals("answer")) {

			mv.addObject("bvo", bvo);
			mv.setViewName("answer/writeinfo.board");
		}

		return mv;
	}

	@RequestMapping("/board/update.do")
	public ModelAndView updateBoard(BoardVO bvo, HttpServletRequest request)
			throws Exception {
		ModelAndView mv = new ModelAndView();
		String type = request.getParameter("type");
		int countView = bvo.getCountView() - 1;
		MultipartFile mfile = bvo.getUploadFile();
		if (type.equals("reply")) {
		if (mfile.isEmpty() == false) {
			// 원본 파일명을 반환
			String fileName = mfile.getOriginalFilename();
			bvo.setOrgfilename(fileName);
			// 시간_파일명으로 변환
			String newfilename = System.currentTimeMillis() + "_" + fileName;
			bvo.setNewfilename(newfilename);
			// 파일 업로드
			File copyFile = new File(path + newfilename);
			mfile.transferTo(copyFile);
		} else {
			bvo.setOrgfilename("");
			bvo.setNewfilename("");
		}
		}else{
			bvo.setOrgfilename("");
			bvo.setNewfilename("");
		}

		boardService.updateBoard(bvo);
		if (type.equals("reply")) {
			mv.setViewName("redirect:/board/detail.do?type=reply&no="
					+ bvo.getNo() + "&countView=" + countView);
		} else if (type.equals("basic")) {
			mv.setViewName("redirect:/board/detail.do?type=basic&no="
					+ bvo.getNo() + "&countView=" + countView);
		} else if (type.equals("answer")) {
			mv.setViewName("redirect:/board/detail.do?type=answer&no="
					+ bvo.getNo() + "&countView=" + countView);
		}

		return mv;

	}

	@RequestMapping("/board/write.do")
	public ModelAndView wirte(BoardVO bvo, HttpServletRequest request)
			throws Exception {
		ModelAndView mv = new ModelAndView();

		String type = request.getParameter("type");
		String id = request.getParameter("id");
		Map map = new HashMap();

		MultipartFile mfile = bvo.getUploadFile();

		if (type.equals("reply")) {
			if (mfile.isEmpty() == false) {
				// 원본 파일명을 반환
				
				String fileName = mfile.getOriginalFilename();
				map.put("orgfilename", fileName);

				// 시간_파일명으로 변환
				String newfilename = System.currentTimeMillis() + "_"
						+ fileName;
				map.put("newfilename", newfilename);

				// 파일 업로드
				File copyFile = new File(path + newfilename);
				mfile.transferTo(copyFile);
			} else{
			map.put("orgfilename", "");
			map.put("newfilename", "");
			}
		}else{
			map.put("orgfilename", "");
			map.put("newfilename", "");
		}
		

		
		map.put("id", id);
		map.put("category", bvo.getCategory());
		map.put("head", bvo.getHead());
		map.put("title", bvo.getTitle());
		map.put("content", bvo.getContent());
		boardService.write(map);

		int no = (int) map.get("board_no");

		if (type.equals("reply")) {
			mv.setViewName("redirect:/board/detail.do?type=reply&no=" + no);
		} else if (type.equals("basic")) {
			mv.setViewName("redirect:/board/detail.do?type=basic&no=" + no);
		} else if (type.equals("answer")) {
			mv.setViewName("redirect:/board/detail.do?type=answer&no=" + no);
		}
		return mv;
	}

	@RequestMapping("/board/answerInfo.do")
	public ModelAndView answerInfo(BoardVO bvo, HttpServletRequest request)
			throws Exception {
		ModelAndView mv = new ModelAndView();

		bvo = boardService.detailView(bvo);

		mv.addObject("bvo", bvo);
		mv.setViewName("answer/answerInfo.board");

		return mv;
	}

	@RequestMapping("/board/answerWrite.do")
	public ModelAndView answer(BoardVO bvo, HttpServletRequest request)
			throws Exception {
		ModelAndView mv = new ModelAndView();
		String id = request.getParameter("id");

		Map map = new HashMap();

		map.put("id", id);
		map.put("ref", bvo.getRef());
		map.put("restep", bvo.getRestep());
		map.put("no", bvo.getNo());

		map.put("category", bvo.getCategory());
		map.put("head", bvo.getHead());
		map.put("title", bvo.getTitle());
		map.put("content", bvo.getContent());
		map.put("relevel", bvo.getRelevel());

		boardService.answerWrite(map);
		int no = (int) map.get("answerno");
		mv.setViewName("redirect:/board/detail.do?type=answer&no=" + no);
		return mv;
	}

	@RequestMapping("/reply/replyWrite.do")
	public String replyWrite(ReplyVO rvo, BoardVO bvo) throws Exception {
		int countView = bvo.getCountView();
		System.out.println(countView + "<-조회수");

		replyService.writeReply(rvo);

		return "redirect:/board/detail.do?no=" + rvo.getBvo().getNo()
				+ "&type=reply&countView=" + (countView - 1);
	}

	@RequestMapping("/reply/replyAnswerWrite.do")
	public String replyAnswerWrite(ReplyVO rvo, HttpServletRequest request)
			throws Exception {
		// System.out.println(rvo);
		int countView = Integer.parseInt(request.getParameter("countView"));

		replyService.replyAnswerWrtie(rvo);
		return "redirect:/board/detail.do?no=" + rvo.getBvo().getNo()
				+ "&type=reply&countView=" + (countView - 1);
	}

	@RequestMapping("/reply/deleteReply.do")
	public String deleteReply(ReplyVO rvo, HttpServletRequest request)
			throws Exception {
		rvo = replyService.replyInfo(rvo);
		int countView = Integer.parseInt(request.getParameter("countView"));
		int no = rvo.getBvo().getNo();
		System.out.println(no);
		System.out.println(rvo.getRno());
		replyService.deleteReply(rvo);

		return "redirect:/board/detail.do?no=" + no + "&type=reply&countView="
				+ (countView - 1);
	}

	@RequestMapping("/board/recentList.do")
	public ModelAndView recentList(BoardVO bvo) throws Exception {
		ModelAndView mv = new ModelAndView();
		List<BoardVO> list = boardService.recentList(bvo);
		mv.addObject("list", list);
		mv.setViewName("recentlist/recentlist.board");
		return mv;
	}

	@RequestMapping("/board/searchBoard.do")
	public ModelAndView searchBoard(BoardVO bvo, HttpServletRequest request)
			throws Exception {
		ModelAndView mv = new ModelAndView();
		String searchType = request.getParameter("searchType");

		String pageNo = request.getParameter("pageNo");

		Map map = new HashMap();
		map.put("head", bvo.getHead());
		map.put("pageNo", pageNo);
		map.put("category", bvo.getCategory());
		ListVO lvo = new ListVO();
		if (searchType.equals("title")) {

			map.put("title", request.getParameter("searchWord"));
			lvo = boardService.searchBoard(map);

		} else if (searchType.equals("content")) {

			map.put("content", request.getParameter("searchWord"));
			System.out.println(map);
			lvo = boardService.searchBoard(map);
			System.out.println("->" + map);
		} else if (searchType.equals("titleContent")) {
			bvo.setTitle(request.getParameter("searchWord"));
			bvo.setContent(request.getParameter("searchWord"));
		} else if (searchType.equals("id")) {

			map.put("id", request.getParameter("searchWord"));
			lvo = boardService.searchBoard(map);
			
		}
		mv.addObject("lvo", lvo);
		mv.setViewName("search/search.board");

		return mv;
	}

	@RequestMapping("/rank.do")
	public ModelAndView showRank() throws Exception {
		ModelAndView mv = new ModelAndView();
		List<RankVO> list = rankService.showRank();
		System.out.println("rank list->"+list);
		mv.addObject("list", list);
		mv.setViewName("search/rank.board");
		return mv;
	}

	private void deleteFile(String newfilename) {
		File f = new File(path + newfilename);
		boolean result = f.delete();
		System.out.println("delete file :" + result);
	}

	@RequestMapping("/board/fileDownload.do")
	public ModelAndView fileDownload(BoardVO bvo) {

		HashMap<String, String> map = new HashMap<String, String>();
		map.put("path", path);
		map.put("orgfilename", bvo.getOrgfilename());
		map.put("newfilename", bvo.getNewfilename());
		System.out.println("fileDownload");
		return new ModelAndView("downloadView", map);
	}

	@RequestMapping("/baord/deletefile.do")
	@ResponseBody
	public String deleteFile(BoardVO bvo) {

		String newfilename = bvo.getNewfilename();

		if (newfilename != null && newfilename.equals("")) {
			deleteFile(newfilename);
		}
		String mess = "삭제되었습니다";
		return mess;
	}
}
